package com.wiloon.tree;

import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * It Reads and prints any RSS/Atom feed type.
 * <p>
 *
 * @author Alejandro Abdelnur
 */
public class FeedReader {
    private static Logger logger = LoggerFactory.getLogger(FeedReader.class);

    public List<News> sync() {
        logger.debug("sync");
        String infoQFeed = "http://www.infoq.com/cn/feed?token=28NnWBwZ7vsg2gW2hUxPTxIMJ6lywqCE";
       String osChinaRss="http://www.oschina.net/news/rss";
        String rssUrl=osChinaRss;
        logger.debug(rssUrl);
        boolean ok = false;
        List<News> newsList = new ArrayList<News>();
        try {
            URL feedUrl = new URL(rssUrl);
            logger.debug("feed url =" + feedUrl.toString());
            SyndFeedInput input = new SyndFeedInput();
            SyndFeed feed = input.build(new XmlReader(feedUrl));
            for(int i=0;i<feed.getEntries().size();i++){
                SyndEntry sei = feed.getEntries().get(i);
                News news = new News();
                news.setTitle(sei.getTitle());
                news.setDescription(sei.getDescription().getValue());
                news.setLink(sei.getLink());
                newsList.add(news);
            }

            ok = true;
            logger.error("read feed success");
        } catch (Exception ex) {
            logger.error("failed to read feed;" + ex);
            ex.printStackTrace();
            System.out.println("ERROR: " + ex.getMessage());
        }


        if (!ok) {
            System.out.println();
            System.out.println("FeedReader reads and prints any RSS/Atom feed type.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }
        logger.debug("news list size="+newsList.size());

        return newsList;
    }

    public static void main(String[] args) {
        new FeedReader().sync();
    }

}